package dimensional.traveler.client.screens.login;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

import dimensional.traveler.client.UserManagement;
import dimensional.traveler.client.mvc.MediatedController;
import dimensional.traveler.client.services.LoginService;
import dimensional.traveler.client.services.LoginServiceAsync;
import dimensional.traveler.client.ui.util.LoadingBar;
import dimensional.traveler.client.ui.util.MessagePopup;
import dimensional.traveler.shared.LoginInfo;

public class LoginController extends MediatedController {
	
	private LoginServiceAsync loginService = GWT.create(LoginService.class);
	
	public void login(final String userName, final String password) {
		
		if (isInvalid(userName, password)) {
			MessagePopup.displayUserError("Empty username");
			return;
		}
		
		LoadingBar.showLoadingBar();
		
		loginService.login(userName, password, new AsyncCallback<LoginInfo>() {
			
			@Override
			public void onSuccess(LoginInfo loginInfo) {
				handleLoginInfo(userName, loginInfo);
			}

			@Override
			public void onFailure(Throwable caught) {
				handleRequestFailure(caught);
			}
		});
		
	}
	
	private boolean isInvalid(String userName, String password) {
		return userName.equals(""); // || userPassword.equals("");
	}
	
	public void createUserAndLogin(final String userName, String userPassword) {
		if (isInvalid(userName, userPassword)) {
			MessagePopup.displayUserError("Empty username");
			return;
		}
		
		LoadingBar.showLoadingBar();
		
		loginService.createUser(userName, userPassword, new AsyncCallback<LoginInfo>() {
			@Override
			public void onSuccess(LoginInfo loginInfo) {
				handleLoginInfo(userName, loginInfo);
			}
			@Override
			public void onFailure(Throwable caught) {
				handleRequestFailure(caught);
			}
		});
	}
	
	private void handleLoginInfo(final String userName, LoginInfo loginInfo) {
		LoadingBar.hideLoadingBar();
		if (loginInfo.loginSuccessful()) {
			UserManagement.setLoggedInUser(userName);
			mediator.displayWelcomeScreen();
		} else {
			MessagePopup.displayUserError(loginInfo.getErrorMessage());
		}
	}
}
